package com.lagou.ipersistence.executor.statement;

import com.lagou.ipersistence.executor.Executor;
import com.lagou.ipersistence.mapping.BoundSql;
import com.lagou.ipersistence.mapping.MappedStatement;
import com.lagou.ipersistence.session.ResultHandler;
import com.lagou.ipersistence.session.RowBounds;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;

/**
 * @author Yan Jiahong
 * Created on 2020/11/22
 */
public class PreparedStatementHandler extends BaseStatementHandler{
    
    public PreparedStatementHandler(Executor executor, MappedStatement mappedStatement, Object parameterObject,
                                    RowBounds rowBounds, ResultHandler<?> resultHandler, BoundSql boundSql) {
        super(executor, mappedStatement, parameterObject, rowBounds, resultHandler, boundSql);
    }
    
    @Override
    protected Statement instantiateStatement(Connection connection) throws SQLException {
        String sql = boundSql.getSql();
        return connection.prepareStatement(sql);
    }
    
    @Override
    public void parameterize(Statement statement) throws SQLException {
        parameterHandler.setParameters((PreparedStatement) statement);
    }
    
    @Override
    public <E> List<E> query(Statement statement, ResultHandler<?> resultHandler) throws SQLException {
        PreparedStatement ps = (PreparedStatement) statement;
        ps.execute();
        return resultSetHandler.handleResultSet(ps);
    }
    
    @Override
    public int update(Statement stmt) throws SQLException{
        PreparedStatement ps = (PreparedStatement) stmt;
        ps.execute();
        return ps.getUpdateCount();
    }
}
